package com.dupf.common.base;

import com.dupf.common.util.PropertiesFileUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.InvalidSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 控制器基类
 * Created by dupf on 2018/3/1.
 */
public abstract class BaseController {

	private final static Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

	/**
	 * 统一异常处理
	 * @param request
	 * @param response
	 * @param exception
	 */
	@ExceptionHandler
	public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) {
		LOGGER.error("统一异常处理：", exception);
		request.setAttribute("ex", exception);
		if (null != request.getHeader("X-Requested-With") && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
			request.setAttribute("requestHeader", "ajax");
		}
		// shiro没有权限异常
		if (exception instanceof UnauthorizedException) {
			return "/403.jsp";
		}
		// shiro会话已过期异常
		if (exception instanceof InvalidSessionException) {
			return "/error.jsp";
		}
		return "/error.jsp";
	}

	/**
	 * 返回jsp视图
	 * @param path
	 * @return
	 */
	public static String jsp(String path) {
		return path.concat(".jsp");
	}

	/**
	 * 返回thymeleaf视图
	 * @param path
	 * @return
	 */
	public static String thymeleaf(String path) {
		String folder = PropertiesFileUtil.getInstance().get("app.name");
		return "/".concat(folder).concat(path).concat(".html");
	}

	protected String getInputStream(HttpServletRequest request) throws IOException {

		String data = getParamData(request);
		if (StringUtils.isNotEmpty(data)) {
			return data;
		}

		// 获取HTTP请求的输入流
		// 已HTTP请求输入流建立一个BufferedReader对象
		BufferedReader br = request.getReader();
		String buffer = null;
		StringBuffer buff = new StringBuffer();
		while ((buffer = br.readLine()) != null) {
			buff.append(buffer + "\n");
		}
		br.close();

		String requestJson = buff.toString().trim();
		String logJson = requestJson.replace("\r", "").replace("\n", "");

		if (request.getServletPath() != null && request.getServletPath().equals("/product/collect-local")) {
			LOGGER.info("ipaddr: " + getIpAddr(request) + ", Content-Type: " + request.getContentType() + ", "
					+ request.getServletPath() + ":" + JSONObject.fromObject(requestJson).optString("url"));
		} else {
			LOGGER.info("ipaddr: " + getIpAddr(request) + ", Content-Type: " + request.getContentType() + ", "
					+ request.getServletPath() + ":" + logJson);
		}
		return requestJson;
	}

	public String getParamData(HttpServletRequest request) {
		Object paramData = request.getAttribute("paramData");
		if (paramData == null) {
			return null;
		}

		LOGGER.info("ContentData:" + paramData.toString());
		return paramData.toString();
	}

	public String getIpAddr(HttpServletRequest request) {
		String ipAddress = null;

		ipAddress = request.getHeader("x-forwarded-for");
		if ((ipAddress == null) || (ipAddress.length() == 0) || ("unknown".equalsIgnoreCase(ipAddress))) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}

		if ((ipAddress == null) || (ipAddress.length() == 0) || ("unknown".equalsIgnoreCase(ipAddress))) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}

		if ((ipAddress == null) || (ipAddress.length() == 0) || ("unknown".equalsIgnoreCase(ipAddress))) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}

				ipAddress = inet.getHostAddress();
			}
		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if ((ipAddress != null) && (ipAddress.length() > 15)) {
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}

		return ipAddress;
	}

}
